package com.tiger.distributelock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

/**
 * attention:
 * expire time setting
 */
@Component
public class RedisDistributeLock implements Lock {
    private static final String OK = "OK";
    // expire time
    private static final long defaultExpireTime = 5 * 1000;


    @Autowired
    private Jedis jedis;

    @Override
    public boolean lock(String resource) {
        return lock(resource, defaultExpireTime);
    }

    @Override
    public boolean lock(String resource, long expireTime) {
        String response = jedis.set(resource, "", "NX", "PX", expireTime);
        return OK.equals(response) ? true : false;
    }

    @Override
    public void unlock(String resource) {
        jedis.del(resource);
    }

}
